//
//  search_labelController.m
//  SoundPill
//
//  Created by 宋鹏鹏 on 15/4/25.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "search_labelController.h"
#import "AppDelegate.h"
#import "UIViewExt.h"
#import "plaza_viewModel.h"
#import "search_worksCell.h"
#import "Find_ActivityTableViewCell.h"
#import "Find_Activity_Model.h"
#import "Player_ShowModel.h"
#import "set_ViewController.h"
#import "RecordViewController.h"
#import "AFNetworking.h"
#import "JSONKit.h"
#import "MJRefresh.h"
#import "MobClick.h"
#import "JCAlertView.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "DownSheet.h"
#import "DownSheetModel.h"
#import "LCActionSheet.h"
#import "WeiboSDK.h"
#import "UIViewController+MMDrawerController.h"
#import "UIImageView+WebCache.h"
#import "UIImage+thumbImage.h"
@interface search_labelController ()<MJRefreshBaseViewDelegate,UIAlertViewDelegate, DownSheetDelegate>
{
    int page;
    int lastPage;
    int pages;
    int enterCount;
    NSString *titleStr;
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
    
//    search_worksCell *_workslistCell;
    UILabel *countlabel;
    UIView *header;
    UILabel *detileLab;
    UIButton *button;
    UIImageView *downDivider;
}

@property (strong, nonatomic) NSString *playingAudioId;
@property (strong, nonatomic)UILabel *titleLabel;
@property (strong, nonatomic) NSArray *menuArray;
@end

@implementation search_labelController
typedef enum {
    NETWORK_TYPE_NONE= 0,
    NETWORK_TYPE_2G= 1,
    NETWORK_TYPE_3G= 2,
    NETWORK_TYPE_4G= 3,
    NETWORK_TYPE_5G= 4,//  5G目前为猜测结果
    NETWORK_TYPE_WIFI= 5,
}NETWORK_TYPE;


- (void)getTitle:(NSString *)title
{
//    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 100)];
//    _titleLabel.text = title;
    titleStr = title;
    self.navigationItem.title = [title stringByReplacingOccurrencesOfString:@"#" withString:@""];
//    self.navigationItem.titleView.frame = CGRectMake(0, 0, 30, 40);
    [self requestData:self.navigationItem.title Page:1 Refreshing:nil];

}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        _listArray = [[NSMutableArray alloc] init];
        DownSheetModel *Model_2 = [[DownSheetModel alloc]init];
        Model_2.icon = @"UMS_wechat_timeline_icon@2x.png";
        Model_2.icon_on = @"UMS_wechat_timeline_icon@2x.png";
        Model_2.title = @"朋友圈";
        DownSheetModel *Model_6 = [[DownSheetModel alloc]init];
        Model_6.icon = @"UMS_wechat_icon@2x.png";
        Model_6.icon_on = @"UMS_wechat_icon@2x.png";
        Model_6.title = @"微信好友";
        DownSheetModel *Model_4 = [[DownSheetModel alloc]init];
        Model_4.icon = @"close";
        Model_4.icon_on = @"close";
        Model_4.title = @"取消";
        DownSheetModel *Model_9 = [[DownSheetModel alloc] init];
        Model_9.icon = @"UMS_sina_icon.png";
        Model_9.icon_on = @"UMS_sina_icon.png";
        Model_9.title = @"新浪微博";
        DownSheetModel *Model_1 = [[DownSheetModel alloc]init];
        Model_1.icon = @"player-fuzhi.png";
        Model_1.icon_on = @"player-fuzhi.png";
        Model_1.title = @"复制链接";
        self.menuArray = [NSArray arrayWithObjects:Model_2,Model_6,Model_9,Model_1,Model_4, nil];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [MobClick beginLogPageView:@"搜索"];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [MobClick endLogPageView:@"搜索"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    lastPage = 1;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.03, self.view.height*0.05, 30, 30)];
    
    backBtn.backgroundColor = [UIColor whiteColor];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
    UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.03, self.view.height*0.05, 30, 30)];
    shareBtn.backgroundColor = [UIColor whiteColor];
    [shareBtn setBackgroundImage:[UIImage imageNamed:@"Play_more"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(menuClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
    self.navigationItem.rightBarButtonItem = shareItem;
    
    //加载表
    _listTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 64)];
//    _listTableView.rowHeight = 65;
    _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _listTableView.dataSource = self;
    _listTableView.delegate = self;
    [self.view addSubview:_listTableView];
    listActivityIndicator = [[UIActivityIndicatorView alloc]
                             initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    listActivityIndicator.frame = CGRectMake(self.view.width/2-20, (self.view.height-108)/2, 40, 40);
    [self.view addSubview:listActivityIndicator];

    [self addRefresh];
}
- (void)checkString:(NSString *)sourceStr withString:(NSString *)targetStr count:(int)count
{
    NSRange ranges;
    ranges = [sourceStr rangeOfString:targetStr];
    if (ranges.location != NSNotFound) {
        NSString *sub = [sourceStr substringFromIndex:ranges.location + 1];
//        NSLog(@"%@",sub);
        count++;
        [self checkString:sub withString:targetStr count:count];
//        return 0;
    } else {
//        NSLog(@"%d",count);
        enterCount = count;
    }
}
- (void)tableViewAddHeader:(NSString *)detileStr
{
    NSString *topicDetile = [NSString stringWithFormat:@"%@", detileStr];
//    [self checkString:topicDetile withString:@"\n" count:0];
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
    CGFloat retSize = [topicDetile boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20 - 70, 200) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingTruncatesLastVisibleLine
            attributes:attribute
            context:nil].size.height;
    if (retSize < 60.00) {
        retSize = 90.00;
    } else {
        retSize = retSize + 50;//+ enterCount * 13 + 20;
    }
    if (!header) {
        header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, retSize)];
    }

    header.frame = CGRectMake(0, 0, self.view.frame.size.width, retSize);
    header.backgroundColor = [UIColor whiteColor];
    
    if ([titleStr rangeOfString:@"#"].location == 0) {
        
        _listTableView.tableHeaderView = header;
    }
    //判断是否有话题描述
    if (!detileLab) {
        UILabel *detileTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 100, 20)];
        detileTitle.text = @"话题描述:";
        detileTitle.textColor = [UIColor colorWithWhite:0.346 alpha:1.000];
        detileTitle.font = [UIFont systemFontOfSize:12];
        [header addSubview:detileTitle];
        detileLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, header.frame.size.width - 20 - 85, header.frame.size.height - 20)];
        [header addSubview:detileLab];
    }
    detileLab.frame = CGRectMake(15, 28, header.frame.size.width - 20 - 70, header.frame.size.height - 20);
    detileLab.numberOfLines = 0;
    detileLab.lineBreakMode = NSLineBreakByWordWrapping;
    detileLab.font = [UIFont systemFontOfSize:13];
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:topicDetile];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    [paragraphStyle setLineSpacing:3.00];//调整行间距
    
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [topicDetile length])];
    detileLab.attributedText = attributedString;
    
    [detileLab sizeToFit];
    
    if (!button) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [header addSubview:button];
    }
    [button setImage:[UIImage imageNamed:@"canJia2"] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    button.frame = CGRectMake(header.frame.size.width - 60, 0, 30, 30 / 0.72);
    button.center = CGPointMake(header.frame.size.width - 35, header.frame.size.height / 2);
    [button addTarget:self action:@selector(searchToRecore) forControlEvents:UIControlEventTouchUpInside];
    
    if (!countlabel) {
        countlabel= [[UILabel alloc] initWithFrame:CGRectMake(0, header.frame.size.height - 20, button.frame.size.width + 20, 20)];
        [header addSubview:countlabel];
    }
    countlabel.frame = CGRectMake(0, header.frame.size.height - 20, button.frame.size.width + 20, 20);
    countlabel.center = CGPointMake(button.center.x, header.frame.size.height - 15);
    countlabel.text = @"共一万条";
    countlabel.textColor = [UIColor grayColor];
    countlabel.textAlignment = NSTextAlignmentCenter;
    countlabel.font = [UIFont systemFontOfSize:10];
    if (!downDivider) {
        downDivider = [[UIImageView alloc] initWithFrame:CGRectMake(0, header.frame.size.height, self.view.frame.size.width, 0.6)];
        downDivider.image = [UIImage imageNamed:@"gray_line"];
        [header addSubview:downDivider];
    }
}

- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)menuClick:(UIButton *)sender
{
    DownSheet *sheet = [[DownSheet alloc]initWithlist:_menuArray height:0];
    sheet.delegate = self;
    [sheet showInViewController:nil];
}
-(void)didSelectIndex:(NSInteger)index
{
    NSString *string3 = [self.navigationItem.title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    search_worksCell *cell = [_listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UIPasteboard *paste = [UIPasteboard generalPasteboard];
    UILabel *customView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
    customView.backgroundColor = [UIColor whiteColor];
    customView.text = @"复制成功!";
    customView.textAlignment = NSTextAlignmentCenter;
    customView.layer.borderColor = [[UIColor blackColor] CGColor];
    customView.layer.borderWidth = 2;
    JCAlertView *_alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
    switch (index) {
        case 0:
        {
            //微信
//            [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
//            [UMSocialData defaultData].extConfig.wechatTimelineData.url = [NSString stringWithFormat:@"http://pillele.cn/playlist.php?topic=%@", string3];//Soundlab
//            [UMSocialData defaultData].extConfig.wechatTimelineData.title = [NSString stringWithFormat:@"#%@# | 声音实验室",self.navigationItem.title];
//            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:[NSString stringWithFormat:@"来声音实验室参加话题 #%@#",self.navigationItem.title] image:(UIImage *)cell._worksImage.image location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
//                if (response.responseCode == UMSResponseCodeSuccess) {
//                    //                        NSLog(@"分享成功！");
//                }
//            }];
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = [NSString stringWithFormat:@"#%@# | 声音实验室",self.navigationItem.title];
            message.description = [NSString stringWithFormat:@"来声音实验室参加话题 #%@#",self.navigationItem.title];
//            [message setThumbImage:(UIImage *)cell._worksImage.image];
            [message setThumbImage:[UIImage generatePhotoThumbnail:(UIImage *)cell._worksImage.image]];
            WXWebpageObject *object = [WXWebpageObject object];
            object.webpageUrl = [NSString stringWithFormat:@"http://pillele.cn/playlist.php?topic=%@", string3];
            message.mediaObject = object;
            SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            req.scene = 1;
//            BOOL result =
            [WXApi sendReq:req];
        }
            break;
        case 1:
           {
               WXMediaMessage *message = [WXMediaMessage message];
               message.title = [NSString stringWithFormat:@"#%@# | 声音实验室",self.navigationItem.title];
               message.description = [NSString stringWithFormat:@"来声音实验室参加话题 #%@#",self.navigationItem.title];
//               ;
               [message setThumbImage:[UIImage generatePhotoThumbnail:(UIImage *)cell._worksImage.image]];
               WXWebpageObject *object = [WXWebpageObject object];
               object.webpageUrl = [NSString stringWithFormat:@"http://pillele.cn/playlist.php?topic=%@", string3];
               message.mediaObject = object;
               SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
               req.bText = NO;
               req.message = message;
               req.scene = 0;
//               BOOL result =
               [WXApi sendReq:req];
           }
            break;
        case 2:{

            WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
            authRequest.redirectURI = @"http://sns.whalecloud.com/sina2/callback";
            authRequest.scope = @"all";
            
            WBMessageObject *message = [WBMessageObject message];
            message.text = [NSString stringWithFormat:@"#%@# \n来 #声音实验室# 参加话题 http://pillele.cn/playlist.php?topic=%@",self.navigationItem.title, string3];//@"#声音实验室#";
            UIImage *thumbImage = cell._worksImage.image;
            WBImageObject *object = [WBImageObject object];
            object.imageData = UIImageJPEGRepresentation(thumbImage, 1);
            message.imageObject = object;
            
            //
            WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:[AppDelegate shareDelegate].wbtoken];
            request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                                 @"Other_Info_1": [NSNumber numberWithInt:123],
                                 @"Other_Info_2": @[@"obj1", @"obj2"],
                                 @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
            [WeiboSDK sendRequest:request];
            break;
        }
        case 3:
            paste.string = [NSString stringWithFormat:@"http://pillele.cn/playlist.php?topic=%@", string3];
            [_alert show];
            [_alert performSelector:@selector(dismissWithCompletion:) withObject:nil afterDelay:1.5];
            break;
        default:
            break;
    }
}
- (void)searchToRecore
{
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] != nil) {
        [AppDelegate shareDelegate].startTag = @"话#题";
        [AppDelegate shareDelegate].topicString = self.navigationItem.title;
        RecordViewController *record = [[RecordViewController alloc] initWithType:[AppDelegate shareDelegate].startTag detile:[AppDelegate shareDelegate].topicString];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:record];
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登陆后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{
            
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];
    }
}

- (void)requestData:(NSString *)string Page:(int)pg Refreshing:(MJRefreshBaseView *)refreshView
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *data = [[NSDictionary alloc]init];

    NSString *string3 = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *fansString=[NSString stringWithFormat:@"http://123.57.1.143/api/work/search?q=%@&by=tag&p=%d",string3,pg];
    [manager GET: fansString parameters:data progress:nil
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSDictionary *dic = [responseObject objectForKey:@"data"];
             NSMutableArray *tempArray = [NSMutableArray array];
             for (NSDictionary *item in dic) {
                 plaza_viewModel *foucsModel = [[plaza_viewModel alloc] init];
                 
                 foucsModel.type = [item objectForKey:@"type"];
                 foucsModel.title =[item objectForKey:@"title"];
                 foucsModel.personName = [[item objectForKey:@"user"] objectForKey:@"username"];
                 foucsModel.UserID = [item objectForKey:@"uid"];
                 foucsModel.CinemeID = [item objectForKey:@"id"];
                 foucsModel.releaseDate = [item objectForKey:@"created_at"];
                 foucsModel.headImageURL = [item objectForKey:@"avatar"];
                 foucsModel.playTimes = [item objectForKey:@"play_count"];
                 foucsModel.heartCount = [item objectForKey:@"love_count"];
                 foucsModel.worksImageURL = [item objectForKey:@"cover"];
                 [tempArray addObject:foucsModel];
             }
             
             [self clearListArray:tempArray];
             NSDictionary *meta = [responseObject valueForKey:@"meta"];
             //        NSLog(@"-----%@", meta);
             if (meta != nil) {
                 pages = [[meta valueForKey:@"pages"] intValue];
                 if (pages == 1 || pg == pages) {
                     _footer.hidden = YES;
                 }
                 if ([[meta valueForKey:@"detail"] length] > 0) {
                     [self tableViewAddHeader:[meta valueForKey:@"detail"]];
                     
                     countlabel.text = [NSString stringWithFormat:@"共 %@ 条",[meta valueForKey:@"total"]];
                 } else {
                     _listTableView.tableHeaderView = nil;
                 }
             }
             [_listTableView reloadData];
             [refreshView endRefreshing];
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             _listTableView.hidden = YES;
             listActivityIndicator.hidden = NO;
             [self performSelector:@selector(hidevicator) withObject:nil afterDelay:1];
    }];
}
- (void)clearListArray:(NSMutableArray *)listArray
{
    for (int i = 0; i <= listArray.count; i=i+2) {
        if (i<listArray.count) {
            if (i + 1 >= listArray.count && i == listArray.count - 1) {
                NSDictionary *tempDic = [[NSDictionary alloc] initWithObjectsAndKeys:listArray[i],@"left", nil];
                [_listArray addObject:tempDic];

            } else {
            NSDictionary *tempDic = [[NSDictionary alloc] initWithObjectsAndKeys:listArray[i],@"left",listArray[i + 1],@"right", nil];
                [_listArray addObject:tempDic];
            }
        } else {
            
        }
    }

}
- (void)hidevicator
{
    [listActivityIndicator stopAnimating];
    listActivityIndicator.hidden = YES;
    [listActivityIndicator removeFromSuperview];
}

#pragma mark 添加刷新控件
- (void)addRefresh
{
    _header = [MJRefreshHeaderView header];
    _header.scrollView = _listTableView;
    _header.delegate = self;
    
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = _listTableView;
    _footer.delegate = self;
}

#pragma mark - 刷新代理方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        _footer.hidden = NO;
        [_listArray removeAllObjects];
        [self requestData:self.navigationItem.title Page:page Refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            _footer.hidden = YES;
        } else {
            page++;
            [self requestData:self.navigationItem.title Page:page Refreshing:refreshView];
        }
    }
}
-(NETWORK_TYPE)getNetworkTypeFromStatusBar {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])     {
            dataNetworkItemView = subview;
            break;
        }
    }
    NETWORK_TYPE nettype = NETWORK_TYPE_NONE;
    NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    nettype = [num intValue];
    return nettype;
}

#pragma mark - TableView DataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return tableView.frame.size.width / 2 * 1.45;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_listArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        // 定义静态标识符
        //static NSString *cellIdentifier = @"cell";
//        NSString *cellIdentifier = @"worklineCell";
//        
//        // 检查表视图中是否存在闲置的单元格
//        _workslistCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//        
//        if (_workslistCell == nil) {
//            
//            _workslistCell = [[search_worksCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
//        }
    
        static NSString *ActivityTableIdentifer = @"activity";
        Find_ActivityTableViewCell *activityCell = [tableView dequeueReusableCellWithIdentifier:ActivityTableIdentifer];
        if (activityCell == nil) {
            activityCell = [[Find_ActivityTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ActivityTableIdentifer];
            activityCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (_listArray.count > 0) {

            plaza_viewModel *leftModel = [_listArray[indexPath.row] valueForKey:@"left"];
            plaza_viewModel *rightModel = [_listArray[indexPath.row] valueForKey:@"right"];
            
            [activityCell.leftButton.bigImage setImageWithURL:[NSURL URLWithString:leftModel.worksImageURL] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
            activityCell.leftButton.workName.text = leftModel.title;
            
            activityCell.leftButton.typeLable.text = @"话题";
           
            activityCell.leftButton.loveImg.image = [UIImage imageNamed:@"love_gray_button"];
            activityCell.leftButton.loveLab.text = leftModel.heartCount;
            activityCell.leftButton.contentImg.image = [UIImage imageNamed:@"Find_labx_content"];
            activityCell.leftButton.contentLab.text = leftModel.playTimes;
            if (leftModel.price.length > 0 || leftModel.price != NULL) {
                activityCell.leftButton.price.text = [NSString stringWithFormat:@"%@元",leftModel.price];
            }
            
            if (rightModel.worksImageURL.length > 0 || rightModel.worksImageURL != NULL) {
                [activityCell.rightButton.bigImage setImageWithURL:[NSURL URLWithString:rightModel.worksImageURL] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
                activityCell.rightButton.workName.text = rightModel.title;
                activityCell.rightButton.typeLable.text = @"话题";
                activityCell.rightButton.contentImg.image = [UIImage imageNamed:@"Find_labx_content"];
                activityCell.rightButton.contentLab.text = rightModel.playTimes;
                activityCell.rightButton.loveImg.image = [UIImage imageNamed:@"love_gray_button"];
                activityCell.rightButton.loveLab.text = rightModel.heartCount;
                if (leftModel.price.length > 0 || leftModel.price != NULL) {
                    activityCell.rightButton.price.text = [NSString stringWithFormat:@"%@元",rightModel.price];
                }
            }
            
            activityCell.rightBlock = ^() {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlayer" object:];
                [self gotoPlayerWithWorkID:rightModel.CinemeID];
            };
            activityCell.leftBlock = ^() {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlayer" object:];
                [self gotoPlayerWithWorkID:leftModel.CinemeID];
            };

        }
//    if (_listArray.count > 0) {
//        
//        _workslistCell.plazadataModel = _listArray[indexPath.row];
//    }
    
    return activityCell;
    
}

#pragma -mark 点击标签cell的跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (void)gotoPlayerWithWorkID:(NSString *)workid
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isPlay = [userDefaults objectForKey:@"isWiFiPlay"];
    NSString *pppp= [NSString stringWithFormat:@"%u",[self getNetworkTypeFromStatusBar]];
    
    if ([[self.navigationController.viewControllers firstObject] isKindOfClass:[playerTableViewController class]]) {
        self.player = (playerTableViewController *)[self.navigationController.viewControllers firstObject];
        if (([isPlay isEqualToString:@"1"]&&[pppp isEqualToString:@"5"])||[pppp isEqualToString:@"5"]||([isPlay isEqualToString:@"0"]&&![pppp isEqualToString:@"0"])||isPlay==nil) {
            
            //播放功能
            Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
//            plaza_viewModel *model = _listArray[indexPath.row];
            
            NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", workid];
            //        NSLog(@"%@", showURL);
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            NSString *requestHeader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
            [manager.requestSerializer setValue:requestHeader forHTTPHeaderField:@"authorization"];
            [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSDictionary *dataDic = [dic valueForKey:@"data"];
                NSDictionary *linksDic = [dic valueForKey:@"links"];
                //            NSLog(@"00000---%@", dataDic);
                [playModel setValuesForKeysWithDictionary:dataDic];
                if ([[dic allKeys] containsObject:@"meta"]) {
                    NSDictionary *meta = [dic valueForKey:@"meta"];
                    NSString *userAvatar = [meta valueForKey:@"userAvatar"];
                    _player.locUserAvatar = userAvatar;
                    //                    NSArray *array = [meta valueForKey:@"playlist"];
                    //                    _player.playList = [NSMutableArray arrayWithArray:array]
                    ;
                }
                if (![_player.workID isEqualToString:playModel.id]) {
                    _player.waveform = [linksDic valueForKey:@"waveform"];
                    _player.workID = workid;
                    _player.isSelf = NO;
                    //保存是否love
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    NSString *islove = @"0";
                    if ([[dataDic objectForKey:@"liked"]boolValue]==YES) {
                        islove = @"1";
                    }else{
                        islove = @"0";
                    }
                    [userDefaults setObject:islove forKey:@"isLove"];
                    [userDefaults synchronize];
                    [_player reloadViews:playModel];
                }
                [self.navigationController popToRootViewControllerAnimated:YES];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        } else{
            [JCAlertView showOneButtonWithTitle:@"你已开启仅Wifi环境播放" Message:@"可以去设置关闭此功能" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }
    } else {
        UINavigationController *nv = (UINavigationController *)self.mm_drawerController.rightDrawerViewController;
        NSArray *array = nv.viewControllers;
        self.player = (playerTableViewController *)[array firstObject];
        if (([isPlay isEqualToString:@"1"]&&[pppp isEqualToString:@"5"])||[pppp isEqualToString:@"5"]||([isPlay isEqualToString:@"0"]&&![pppp isEqualToString:@"0"])||isPlay==nil) {
            
            //播放功能
            Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
//            plaza_viewModel *model = _listArray[indexPath.row];
            
            NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", workid];
            //        NSLog(@"%@", showURL);
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            NSString *requestHeader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
            [manager.requestSerializer setValue:requestHeader forHTTPHeaderField:@"authorization"];
            [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSDictionary *dataDic = [dic valueForKey:@"data"];
                NSDictionary *linksDic = [dic valueForKey:@"links"];
                //            NSLog(@"00000---%@", dataDic);
                [playModel setValuesForKeysWithDictionary:dataDic];
                if ([[dic allKeys] containsObject:@"meta"]) {
                    NSDictionary *meta = [dic valueForKey:@"meta"];
                    NSString *userAvatar = [meta valueForKey:@"userAvatar"];
                    _player.locUserAvatar = userAvatar;
                    playModel.comment_count = [meta valueForKey:@"count"];
                    ;
                }
                if (![_player.workID isEqualToString:playModel.id]) {
                    _player.waveform = [linksDic valueForKey:@"waveform"];
                    _player.workID = workid;
                    _player.isSelf = NO;
                    //保存是否love
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    NSString *islove = @"0";
                    if ([[dataDic objectForKey:@"liked"]boolValue]==YES) {
                        islove = @"1";
                    }else{
                        islove = @"0";
                    }
                    [userDefaults setObject:islove forKey:@"isLove"];
                    [userDefaults synchronize];
                    [_player reloadViews:playModel];
                }
                [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
                }];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        } else{
            [JCAlertView showOneButtonWithTitle:@"你已开启仅Wifi环境播放" Message:@"可以去设置关闭此功能" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }
    }
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag==80003) {
        if (buttonIndex == 0) {
            
        }else if (buttonIndex == 1){
            
            //跳到设置
            set_ViewController *setVC = [[set_ViewController alloc]init];
            [self.navigationController pushViewController:setVC animated:YES];
            
        }
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
